package com.aspire.query.service.impl;

import com.aspire.query.constant.SysConstant;
import com.aspire.query.dao.QueryInfoDao;
import com.aspire.query.service.QueryInfo;
import com.aspire.query.service.QueryInfoTwo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhouyumin
 */
@Service
@Slf4j
public class QueryInfoImplTwo implements QueryInfoTwo {

    @Autowired
    private QueryInfoDao queryInfoDao;

    private BufferedWriter bufferedWriter;

    @Override
    public void query(String sql) {

        String fileName = getFileName();
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(fileName));
            String test = "select column_name from information_schema.columns where table_name = 'query' and table_schema = 'test'";
            List<LinkedHashMap<String, Object>> queryList = queryInfoDao.query(sql);
            // 写表头
            writeHeader(queryList);
            // 写数据
            for (int i = 0; i < queryList.size(); i++) {
                String line = "";

                LinkedHashMap<String, Object> map = queryList.get(i);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    Object object = entry.getValue();
                    String value = "";
                    if (object != null) {
                        value = object.toString();
                    }
                    line = line.concat(value).concat(SysConstant.CSV_SPILT);
                }
                bufferedWriter.newLine();
                bufferedWriter.write(line);
            }
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入表头
     * @param map
     * @throws IOException
     */
    private void writeHeader(List<LinkedHashMap<String,Object>> map) throws IOException {
        String headerLine = "";
        for (Map.Entry<String, Object> entry : map.get(0).entrySet()) {
            // 获取表头
            headerLine = headerLine.concat(entry.getKey().concat(SysConstant.CSV_SPILT));
        }
        // 去除表头结尾的逗号
        headerLine = headerLine.substring(0 , headerLine.length()-1);
        log.info("headerLine={}", headerLine);
        bufferedWriter.write(headerLine);
    }

    /**
     * 获取文件名称 ：csv文件以表名加日期生成（表名前缀固定为query）
     * @return
     */
    private String getFileName() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String dateTimeInfo = dateFormat.format(new Date());
        return SysConstant.CSV_FILE_NAME_PREFIX.concat(String.format("_%s.csv", dateTimeInfo));
    }
}
